(function() {
    angular.module('app').factory('util', util);

    util.$inject = ['$http', '$q', '$rootScope','$window'];

    function util($http, $q, $rootScope,$window) {
        return {
            $get: _get,
            $post: _post,
            $broadcast: _broadcast,
            $on: _on,
            bigNumFormat: _bigNumFormat,
            catNameFormat: _catNameFormat,
            historyFormat: _historyFormat,
            shopLevelFormat: _shopLevelFormat,
            dateFormat: _dateFormat,

            //user
            returnUserIndustryType: _returnUserIndustryType,
            returnUserIndustry: _returnIndustry
        }

        function _get(param) {
            if (!param instanceof Object || !param.url) {
                return;
            }
            var defer = $q.defer();
            $http({
                method: 'GET',
                url: param.url,
                params: param.data || {},
                headers: {
                    'Accept': 'application/json, text/javascript, */*'
                }
            }).then(function(resp) {

                var resp = resp.data;


                if (resp.success) {
                    defer.resolve(resp);
                } else {
                    defer.reject(resp);

                    if (resp.value == "session expire") {
                        $window.location.href = "login.html";
                        return;
                    }

                }
            }, function(err) {

                var err = err.data; 

                defer.reject(err);
            });

            return defer.promise;
        }

        function _post(param) {
            if (!param instanceof Object || !param.url) {
                return;
            }

            var defer = $q.defer();
            //{url:xx:data:{xx:xx}}          
            $http({
                method: 'post',
                url: param.url,
                data: param.data,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: function(obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                }
            }).then(function(resp) {

                var resp = resp.data;

                if (resp.success) {
                    defer.resolve(resp);
                } else {
                    defer.reject(resp);

                    if (resp.value == "session expire") {
                        $window.location.href = "login.html";
                        return;
                    }
                }
            }, function(err) {


                var err = resp.data;

                defer.reject(err);
            });

            return defer.promise;
        }

        function _broadcast(ev, data) {
            $rootScope.$emit(ev, data);
        }

        function _on(scope, ev, callback) {
            if (!scope.EVENT_OFF) {
                scope.EVENT_OFF = [];
            }
            console.log('is $on:' + eventName);
            scope.EVENT_OFF[eventName] = $rootScope.$on(ev, callback);
            scope.$on('$destroy', function() {
                // console.log(scope);
                for (var i in scope.EVENT_OFF) {
                    console.log('destory:' + i);
                    scope.EVENT_OFF[i]();
                }
            });

        }

        function _bigNumFormat(num) {

            num = Number(Number(num).toFixed(0));

            var len = String(num).length;

            if (num < 10000) {
                return num;
            }

            switch (len) {
                case 5:
                    return (num / 10000).toFixed(2) + '万';
                case 6:
                    return (num / 10000).toFixed(2) + '万';
                case 7:
                    return (num / 10000).toFixed(2) + '万';
                case 8:
                    return (num / 10000).toFixed(2) + '万';
                case 9:
                    return (num / 100000000).toFixed(2) + '亿';
                case 10:
                    return (num / 100000000).toFixed(2) + '亿';
                case 11:
                    return (num / 100000000).toFixed(2) + '亿';
                case 12:
                    return (num / 100000000).toFixed(2) + '亿';
            }

            return num;
        }


        function _catNameFormat(catName) {
            if (catName == '/') {
                return "全网";
            } else if (catName.indexOf('--') == -1) {
                return catName;
            } else {
                return catName.split('--')[catName.split('--').length - 1];
            }
        }

        function _historyFormat(stringHistory) {
            var x = [];
            var y = [];
            if (stringHistory.length > 0) {
                //'2017-01-16=83966' 一条记录            
                if (stringHistory.indexOf(';') == -1) {
                    var temp = stringHistory.split('=');
                    x.push(temp[0]);
                    y.push(temp[1]);
                } else {
                    //多条记录
                    var arr = stringHistory.split(';');
                    for (var k in arr) {
                        var temp = arr[k].split('=');
                        x.push(temp[0]);
                        y.push(temp[1]);
                    }
                }
            }

            return {
                x: x,
                y: y
            }
        }


        function _shopLevelFormat(shop) {
            if (shop.shopLevel >= 1 && shop.shopLevel <= 5) {
                shop.shopLevelType = 1;
            } else if (shop.shopLevel >= 6 && shop.shopLevel <= 10) {
                shop.shopLevelType = 2;
            } else if (shop.shopLevel >= 11 && shop.shopLevel <= 15) {
                shop.shopLevelType = 3;
            } else {
                shop.shopLevelType = 4;
            }

            shop.shopLevel = (shop.shopLevel - 1) % 5 + 1;
            shop.shopLevels = new Array(shop.shopLevel);

            if (shop.sellAmount == 0) {
                shop.avgPrice = 0;
            } else {
                shop.avgPrice = (shop.sellMoney / shop.sellAmount).toFixed(2) + '元';
            }

            return shop;
        }


        function _dateFormat(date) {

            var setTime = angular.isString(date) ? date : date.toString();

            return setTime.substring(0, 10);

        }

        function _returnIndustry(user) {

            var version = user.version;

            var itemLevel1Category = user.itemLevel1Category;



            var industry;

            if (version.indexOf('v1') != -1) { //全行业

                industry = '全行业';

                user.industry_type = 'all';

            } else if (version.indexOf('v2') != -1) { //多行业

                if (typeof itemLevel1Category == 'undefined' || itemLevel1Category.length == 0) {
                    industry = "";
                } else {
                    var arry = itemLevel1Category.split(';');

                    industry = [];

                    for (var i in arry) {
                        industry.push(arry[i].split('--')[1]);
                    }


                }

                user.industry_type = 'mutil';
            } else {

                if (itemLevel1Category == null || itemLevel1Category.length == 0) {
                    industry = "";
                } else {
                    industry = itemLevel1Category.split('--')[1];
                }


                user.industry_type = 'singel';
            }

            return industry;
        }


        function _returnUserIndustryType(user) {

            var version = user.version;
            var type;

            if (version.indexOf('v1') != -1) { //全行业

                type = 'all';
            } else if (version.indexOf('v2') != -1) { //多行业

                type = 'multi';
            } else {

                type = 'singel';
            }

            return type;

        }
    }

})();
